package com.haiertvbic.tvnow;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.haiertvbic.tvnow.util.Util;

public class OttWebViewActivity extends Activity {
	private Activity context = OttWebViewActivity.this;
	private WebView ottWebView;
	private LinearLayout anim;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity4_ott2_webview);
		initWebView();
	}

	private void initWebView() {
		anim = (LinearLayout) findViewById(R.id.anim);
		ottWebView = (WebView) findViewById(R.id.webview_ott);
		WebSettings webSetting = ottWebView.getSettings();
		webSetting.setJavaScriptEnabled(true);
		webSetting.setPluginsEnabled(true);
		webSetting.setPluginState(WebSettings.PluginState.ON);
		ottWebView.setWebViewClient(new MyWebViewClient());

		Intent intent = getIntent();
		String ottUrl = intent.getStringExtra("OTT_URL");
		ottWebView.loadUrl(ottUrl);
	}

	public void startAnim() {
		Animation inAnimation = AnimationUtils.loadAnimation(this,
				R.anim.slide_in_right);
		inAnimation.setStartOffset(100);
		anim.startAnimation(inAnimation);
	}

	@Override
	protected void onResume() {
		Util.initToOtherApk(context);
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		if (loadingBar != null && loadingBar.isShowing()) {
			loadingBar.dismiss();
		}
		super.onDestroy();
	}

	private ProgressDialog loadingBar;

	private class MyWebViewClient extends WebViewClient {

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			loadingBar = ProgressDialog.show(context, null, "正在加载…");
			if (loadingBar != null) {
				loadingBar.setCancelable(true);
			}
			super.onPageStarted(view, url, favicon);
		}

		/**
		 * 返回true表示在同一个浏览器内加载
		 */
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// view.loadUrl(url); // webview里面的链接还在同一个页面中加载
			// 开启浏览器意图
			Util.startBrower(url, context);
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			if (loadingBar != null && loadingBar.isShowing()) {
				loadingBar.dismiss();
			}
			super.onPageFinished(view, url);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			Toast.makeText(context, "加载出错！", Toast.LENGTH_LONG).show();
		}
	}
}
